package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Person struct {
	// `uri:"id"` 是字段的tag,表示字段可以从 uri 中获取, 名称是 id
	ID   int    `uri:"id"`
	Name string `uri:"name"`
}

func main() {

	r := gin.Default()

	//http://localhost:8080/posts/159/gin
	r.GET("/posts/:id/:name", func(c *gin.Context) {
		var p Person
		//这里可以通过 Person 对id和name的类型进行限定
		//数据绑定 c.ShouldBindUri(&p) 将uri参数绑定到Person上
		if err := c.ShouldBindUri(&p); err != nil {
			c.Status(http.StatusNotFound)
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"id":   p.ID,
			"name": p.Name,
		})
	})

	//取查询参数
	//http://localhost:8080/welcome?firstName=gin1&lastName=soul2
	r.GET("/welcome", welcomeHandler)

	//取查询参数中的数组
	//http://localhost:8080/array?ids=123,456,789
	r.GET("/array", arrayHandler)
	//取查询参数中的map
	//http://localhost:8080/map?user[name]=gin&user[age]=28
	r.GET("/map", mapHandler)

	//POST 表单提交
	//http://localhost:8080/form
	// postman
	// message:helloMsg
	r.POST("/form", formHandler)

	//http://localhost:8080/form/array
	// postman
	// ids:123,456,789
	r.POST("/form/array", formArrayHandler)

	//http://localhost:8080/form/map
	// postman bulk edit
	// user[name]:soul_gin
	// user[age]:28
	r.POST("/form/map", formMapHandler)

	//uri携带参数, form也携带参数
	// http://localhost:8080/user/123
	// postman bulk edit
	// userName:soul_gin
	r.POST("user/:id", func(c *gin.Context) {
		id := c.Param("id")
		userName := c.PostForm("userName")
		c.JSON(http.StatusOK, gin.H{
			"id":       id,
			"userName": userName,
		})
	})

	r.Run()
}

func formArrayHandler(c *gin.Context) {
	ids := c.PostFormArray("ids")
	c.JSON(http.StatusOK, gin.H{
		"ids": ids,
	})
}

func formMapHandler(c *gin.Context) {
	user := c.PostFormMap("user")

	c.JSON(http.StatusOK, gin.H{
		"data": user,
	})
}

func formHandler(c *gin.Context) {
	message := c.PostForm("message")
	//没有值的时候取默认值 gin
	name := c.DefaultPostForm("name", "gin")
	c.JSON(200, gin.H{
		"message": message,
		"name":    name,
	})
}

func mapHandler(c *gin.Context) {
	m := c.QueryMap("user")
	c.JSON(200, gin.H{
		"data": m,
	})
}

func arrayHandler(c *gin.Context) {
	ids := c.QueryArray("ids")
	c.JSON(http.StatusOK, gin.H{
		"ids": ids,
	})
}

func welcomeHandler(c *gin.Context) {
	firstName := c.DefaultQuery("firstName", "gin")
	lastName := c.DefaultQuery("lastName", "soul")

	c.JSON(http.StatusOK, gin.H{
		"firstName": firstName,
		"lastName":  lastName,
	})
}
